package com.yurendao.shop.user.service.impl;

import com.yurendao.shop.user.domain.User;
import com.yurendao.shop.user.service.exception.UserException;

/**
 * Created by kong on 16/1/13.
 */
public class UserValidate {

    /**
     * 非空校验
     * @param value
     * @param errorcode
     * @throws UserException
     */
    public static void notNull(String value,String errorcode) throws UserException{
        if(value==null||value.trim()=="")
            throw new UserException(errorcode);
    }

    /**
     * 非法字符
     * @param value
     * @param errorcode
     * @throws UserException
     */
    public static void matchWord(String value,String errorcode) throws UserException{
        if(!value.matches("[a-zA-Z0-9_\u4e00-\u9fa5]*"))
            throw new UserException(errorcode);
    }

/**
 * 
 * @param email
 * @param errorcode
 * @return
 * @throws UserException 
 */
    public static boolean matchEmail(String email,String errorcode) throws UserException{
        boolean flag = false;
        if(email.contains("@")){
            flag =  true;
        }
        else 
            throw new UserException(errorcode);
        return flag;
    }

    
    /**
     * 长度校验
     * @param value
     * @param min
     * @param max
     * @param errorcode
     * @throws UserException
     */
    public static void wordLength(String value,int min,int max,String errorcode) throws UserException{
        if(value.length()<min||value.length()>max)
            throw new UserException(errorcode);
    }

    public static void validate(User user,String type) throws UserException {
        notNull(user.getUname(), "101");
        matchWord(user.getUname(),"102");
        wordLength(user.getUname(),3,32,"103");
        notNull(user.getPassword(),"201");
        matchWord(user.getPassword(),"202");
        wordLength(user.getPassword(),3,9,"203");
        if(type=="email"){
            matchEmail(user.getEmail(),"301");
            wordLength(user.getPhone(),11,11,"302");
        }
    }
}
